﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Input;
using MyWindowsMediaPlayer.Libs.Mediator;
using MyWindowsMediaPlayer.Libs.ViewModel;
using MyWindowsMediaPlayer.Models;

namespace MyWindowsMediaPlayer.ViewModels.Playlist
{
	public class PlaylistViewModel : ViewModelBase
	{
		#region Members

		ObservableCollection<MediaViewModel> _items;
		ICollectionView _collectionView;
		Mediator _mediator;

		#endregion

		#region Constructor

		public PlaylistViewModel ( Mediator mediator )
		{
			this._items = new ObservableCollection<MediaViewModel>();
			this._collectionView = CollectionViewSource.GetDefaultView(this._items);
			this._mediator = mediator;
			this._mediator.Register(MediatorMessage.CenterItemSelected,
				param =>
				{
					this._items.Add( (MediaViewModel)param );
					this._mediator.NotifyColleagues(MediatorMessage.CurrentRead, ((MediaViewModel)param).ItemPath);
				});
			this._mediator.Register(MediatorMessage.NextItem,
				param =>
				{
					this._collectionView.MoveCurrentToNext();
					if (this._collectionView.IsCurrentAfterLast)
						this._collectionView.MoveCurrentToPrevious();
					else
						this._mediator.NotifyColleagues(MediatorMessage.CurrentRead, ((MediaViewModel)this._collectionView.CurrentItem).ItemPath);
				});
			this._mediator.Register(MediatorMessage.PrevItem,
				param =>
				{
					this._collectionView.MoveCurrentToPrevious();
					if (this._collectionView.IsCurrentBeforeFirst)
						this._collectionView.MoveCurrentToNext();
					else
						this._mediator.NotifyColleagues(MediatorMessage.CurrentRead, ((MediaViewModel)this._collectionView.CurrentItem).ItemPath);
				});
		}

		#endregion

		#region Accessors

		public ObservableCollection<MediaViewModel> Items
		{
			get { return this._items; }
		}

		public MediaViewModel SelectedMedia
		{
			get { return this._collectionView.CurrentItem as MediaViewModel; }
		}

		#endregion
	}
}
